package cn.wolfcode.crm.execption;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class CRMExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public String handleException(Exception ex, Model model, HandlerMethod handlerMethod, HttpServletResponse response) throws ServletException, IOException {
        //把异常信息打印出来,方便找bug
        ex.printStackTrace();
        //判断当前请求是否是ajax请求,看当前方法是否贴了ajax对应的注解(ResponseBody)
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            JsonResult jsonResult = new JsonResult(false, "操作失败,请联系管理员!");
            //设置字符串编码
            response.setContentType("application/json;charset=utf-8");
            //使用写入流返回json对象
            response.getWriter().print(JSON.toJSONString(jsonResult));
            return null;
        }
        //如果不是,就返回视图
        model.addAttribute("ex", ex);
        return "common/error";
    }

    /*
        springMVC 整合 shiro 时，
        配置了当访问某个URL没有权限时的配置处理
    */
    @ExceptionHandler(UnauthorizedException.class)
    public String handleUnauthorizedException(Exception ex, Model model, HandlerMethod handlerMethod, HttpServletResponse response) throws ServletException, IOException {
        //把异常信息打印出来,方便找bug
        ex.printStackTrace();
        //判断当前请求是否是ajax请求,看当前方法是否贴了ajax对应的注解(ResponseBody)
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            JsonResult jsonResult = new JsonResult(false, "您暂无该权限,请联系管理员!");
            //设置字符串编码
            response.setContentType("application/json;charset=utf-8");
            //使用写入流返回json对象
            response.getWriter().print(JSON.toJSONString(jsonResult));
            return null;
        }
        //如果不是,就返回视图
        model.addAttribute("ex", ex);
        return "common/nopermission";
    }
}
